package GUILayer;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;


import ControlLayer.InvoiceCtr;

import ModelLayer.Invoice;

public class InvoiceGUI extends JPanel {
	private static final long serialVersionUID = 1L;
	private InvoiceCtr invoiceCtr;
	private DefaultTableModel invoiceTableModel;
	private JScrollPane invoiceTableScrollPane;
	private JPanel showAllInvoicePanel;
	private JTable showAllInvoiceTable;
	private JPanel invoiceInfoPanel;
	private JPanel choicePanel;


	private JTextField textField_searchId;
	private JTextField textField_invoiceNo;
	private JTextField textField_custId;
	private JTextField textField_payDate;
	private JTextField textField_totalPrice;
	private JTextField textField_isDelivery;
	private JTextField textField_isCashOnDeliery;
	
	

	private JButton btnSave;
	private JButton btnCreate;
	private JButton btnEdit;
	private JButton btnCancel;
	private JButton btnDelete;



	public InvoiceGUI() {
		invoiceCtr = new InvoiceCtr();
		initialize();
	}

	public void initialize() {
		this.setLayout(new BorderLayout());

		showAllInvoicePanel = new JPanel();
		this.add(showAllInvoicePanel, BorderLayout.CENTER);
		showAllInvoicePanel.setBorder(BorderFactory
				.createTitledBorder("Invoice Info"));
		showAllInvoicePanel.setLayout(new BorderLayout());

		textField_searchId = new JTextField();
		textField_searchId.setColumns(10);
		JButton btnSearch = new JButton("Search");
		
		JLabel lblId = new JLabel("Id: ");

		JPanel searchPanel = new JPanel();
		searchPanel.setLayout(new FlowLayout());
		searchPanel.add(lblId);
		searchPanel.add(textField_searchId);
		searchPanel.add(btnSearch);
		showAllInvoicePanel.add(searchPanel, BorderLayout.NORTH);

		// show customer info view
		JPanel showInvoicePanel = new JPanel();
		this.add(showInvoicePanel, BorderLayout.EAST);
		showInvoicePanel.setLayout(new BorderLayout());
		showInvoicePanel.setBorder(BorderFactory
				.createTitledBorder("Invoice"));

		invoiceInfoPanel = new JPanel();
		JLabel lblinvoiceNo = new JLabel("Invoice Nr: ");
		JLabel lblcustId = new JLabel("Customer Id: ");
		JLabel lblpayDate = new JLabel("Pay Date(dd/mm/yyyy): ");
		JLabel lbltotalPrice = new JLabel("Total Price: ");
		JLabel lblisDelivery = new JLabel("Delivered: ");
		JLabel lblisCashOnDelivery = new JLabel("Cash On Delivery: ");
		
		textField_invoiceNo = 	new JTextField();
		textField_invoiceNo.setEditable(false); // Id is not able changed
		
		textField_custId = new JTextField();
		textField_payDate = new JTextField();
		textField_totalPrice = new JTextField();
		textField_isDelivery= new JTextField();
		textField_isCashOnDeliery= new JTextField();


	
		GroupLayout gl = new GroupLayout(invoiceInfoPanel);
		invoiceInfoPanel.setLayout(gl);
		invoiceInfoPanel.setBorder(BorderFactory.createTitledBorder("Info"));
		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

		gl.setHorizontalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblinvoiceNo)
								.addComponent(lblcustId)
								.addComponent(lblpayDate)
								.addComponent(lbltotalPrice)
								.addComponent(lblisDelivery)
								.addComponent(lblisCashOnDelivery)
								
								)
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(textField_invoiceNo)
								.addComponent(textField_custId)
								.addComponent(textField_payDate)
								.addComponent(textField_totalPrice)
								.addComponent(textField_isDelivery)
								.addComponent(textField_isCashOnDeliery)
								));
		gl.setVerticalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblinvoiceNo)
								.addComponent(textField_invoiceNo))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblcustId)
								.addComponent(textField_custId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblpayDate)
								.addComponent(textField_payDate))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lbltotalPrice)
								.addComponent(textField_totalPrice))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblisDelivery)
								.addComponent(textField_isDelivery))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblisCashOnDelivery)
								.addComponent(textField_isCashOnDeliery))
				);

		showInvoicePanel.add(invoiceInfoPanel, BorderLayout.NORTH);

		choicePanel = new JPanel();
		choicePanel.setLayout(new FlowLayout());
		btnCreate = new JButton("Create");
		btnEdit = new JButton("Edit");
		btnDelete = new JButton("Delete");
		btnSave = new JButton("Save");
		btnCancel = new JButton("Cancel/Clear");

		choicePanel.add(btnCreate);
		choicePanel.add(btnEdit);
		choicePanel.add(btnSave);
		choicePanel.add(btnDelete);
		choicePanel.add(btnCancel);
		showInvoicePanel.add(choicePanel, BorderLayout.CENTER);
		setBtnStartStatue();

		addInvoiceTable();
		showAllInvoice();

		// button function
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (showInvoice(getTextFieldId(textField_searchId))) {
					textField_searchId.setText("");
					setBtnEditStatue();
					isTextFieldEditable(false);
				}
			}
		});

		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Date payDate;
				
				try {
					payDate = new SimpleDateFormat("dd/MM/yyyy")
					.parse(textField_payDate.getText());
					invoiceCtr.insertInvoice(Integer.parseInt(textField_custId.getText()), payDate, 0, false, false);
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				catch (Exception ex) {
					JOptionPane.showMessageDialog(null, "Please input correct values", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
				cleanTextField();
				showAllInvoice();
			}
		});
		// TODO
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int reply = JOptionPane.showConfirmDialog(null,
						"Do you want to delete this invoice ?",
						"Delete Invoice", JOptionPane.YES_NO_OPTION,
						JOptionPane.WARNING_MESSAGE);
				if (reply == JOptionPane.YES_OPTION) {
					try {
						invoiceCtr.deleteInvoice(Integer
								.parseInt(textField_invoiceNo.getText()));
						cleanTextField();
						setBtnStartStatue();
						showAllInvoice();
					} catch (Exception e1) {
					}
				}
			}
		});

		btnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				isTextFieldEditable(true);
				btnSave.setEnabled(true);
				btnDelete.setEnabled(true);
				btnCreate.setEnabled(false);
			}
		});

		btnSave.addActionListener(new ActionListener() {
		

			public void actionPerformed(ActionEvent e) {
				try {
				
				invoiceCtr.updateInvoice(
						Integer.parseInt(textField_invoiceNo.getText()),
						Integer.parseInt(textField_custId.getText()),
						new SimpleDateFormat("dd/MM/yyyy")
						.parse(textField_payDate.getText()), Double.parseDouble(textField_totalPrice.getText()), 
						Boolean.parseBoolean(textField_isDelivery.getText()),
						Boolean.parseBoolean(textField_isCashOnDeliery.getText()));
				} catch (Exception a) {
					JOptionPane.showMessageDialog(null, "Please input correct values", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
				
				setBtnStartStatue();
				showAllInvoice();
			}
		});

		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cleanTextField();
				isTextFieldEditable(true);
				setBtnStartStatue();
			}
		});

	}

	public void addInvoiceTable() {
		invoiceTableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		invoiceTableModel.addColumn("ID");
		invoiceTableModel.addColumn("Customer Id");
		invoiceTableModel.addColumn("Pay Date");
		invoiceTableModel.addColumn("Total Price");
		invoiceTableModel.addColumn("Delivered");
		invoiceTableModel.addColumn("Cash On Delivery");
		
		invoiceTableScrollPane = new JScrollPane();

		showAllInvoicePanel.add(invoiceTableScrollPane, BorderLayout.CENTER);

		showAllInvoiceTable = new JTable(invoiceTableModel);
		showAllInvoiceTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		showAllInvoiceTable.setAutoCreateRowSorter(true);

		showAllInvoiceTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				btnCreate.setEnabled(false);
				btnEdit.setEnabled(true);
				int row = showAllInvoiceTable.rowAtPoint(e.getPoint());
				if (e.getClickCount() == 2) {
					if (showInvoice(Integer
							.valueOf((Integer) showAllInvoiceTable.getValueAt(
									row, 0)))) {
					}
				}
			}
		});
		invoiceTableScrollPane.setViewportView(showAllInvoiceTable);
	}

	public void showAllInvoice() {
		ArrayList<Invoice> invoices = invoiceCtr.getAllInvoice();
		invoiceTableModel.setRowCount(0);
		for (Invoice invoice : invoices) {
			try {
				//TODO 
				invoiceTableModel.addRow(new Object[] { invoice.getInvoiceNo(),
						invoice.getCustomer().getId(), new SimpleDateFormat("dd/MM/yyyy").format(invoice
								.getPayDate()), invoice.getTotalPrice(), invoice.isDelivery(), invoice.isCashOnDelivery() });
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, e, "Error",
						JOptionPane.ERROR_MESSAGE);
			}
		}

	}

	public boolean showInvoice(int invoiceNo) {
		boolean success = true;
		Invoice invoice = null;
		try {
			if (invoiceNo != 0) {
				invoice = invoiceCtr.getInvoice(invoiceNo);
			}
		} catch (Exception e) {
			success = false;
			JOptionPane.showMessageDialog(null, e, "Error",
					JOptionPane.ERROR_MESSAGE);
			return success;
		}

		if (success) {
			textField_invoiceNo.setText(Integer.toString(invoice.getInvoiceNo()));
			textField_custId.setText(Integer.toString(invoice.getCustomer().getId()));
			textField_payDate.setText(new SimpleDateFormat("dd/MM/yyyy")
			.format(invoice.getPayDate()));
			textField_totalPrice.setText(Double.toString(invoice.getTotalPrice()));
			textField_isDelivery.setText(Boolean.toString(invoice.isDelivery()));
			textField_isCashOnDeliery.setText(Boolean.toString(invoice.isCashOnDelivery()));
			isTextFieldEditable(false);
		}
		return success;
	}

	public void isTextFieldEditable(boolean isEditable) {
		
		textField_custId.setEditable(isEditable);
		textField_isCashOnDeliery.setEditable(isEditable);
		textField_isDelivery.setEditable(isEditable);
		textField_payDate.setEditable(isEditable);
		textField_totalPrice.setEditable(isEditable);
		
	}

	public int getTextFieldId(JTextField textField) {
		int id = 0;
		try {
			id = Integer.parseInt(textField.getText());
		} catch (NumberFormatException e) {
			JOptionPane.showMessageDialog(null, "Please input number", "Error",
					JOptionPane.ERROR_MESSAGE);
		} finally {
			textField.setText("");
		}
		return id;
	}

	public void setBtnStartStatue() {
		btnCreate.setEnabled(true);
		btnEdit.setEnabled(false);
		btnDelete.setEnabled(false);
		btnSave.setEnabled(false);
	}

	public void setBtnEditStatue() {
		btnCreate.setEnabled(false);
		btnEdit.setEnabled(true);
		btnDelete.setEnabled(true);
		btnSave.setEnabled(true);
	}

	public void cleanTextField() {
		textField_searchId.setText("");
		textField_invoiceNo.setText("");
		textField_custId.setText("");
		textField_isCashOnDeliery.setText("");
		textField_isDelivery.setText("");
		textField_totalPrice.setText("");
		textField_payDate.setText("");
	}
}
